package org.subatu.orm.query.condition;


import org.subatu.orm.query.base.BaseSql;
import org.subatu.orm.query.brige.WhereJoin;
import org.subatu.orm.query.table.TableDef;
import org.subatu.orm.util.ChkUtil;
import org.subatu.orm.util.SqlUtil;

/**
 * 查询
 */
public interface From<T extends WhereJoin> extends BaseSql {

    // StringBuilder sqlData().fromSql = new StringBuilder();

    default T from(Class<?> fromTableClass) {
        return this.from(fromTableClass, null);
    }

    default T from(Class<?> fromTableClass, String alias) {
        String tableName = SqlUtil.getTableName(fromTableClass);

        TableDef tableDef = new TableDef();
        tableDef.setTableName(tableName);
        tableDef.setAlias(alias);
        this.sqlData().tableAliasMap.put(tableDef.getTableName(), alias);

        this.sqlData().fromTable.add(tableDef);
        return (T) this;
    }

    default T from(String tableName) {
        sqlData().fromSql.append(" from " + tableName + " ");
        return (T) this;
    }

    default String buildFromSql() {
        if (sqlData().fromSql.length() > 0 || this.sqlData().fromTable.size() == 0) {
            // 如果手工设置了 sql, 直接返回
            return sqlData().fromSql.toString();
        }
        sqlData().fromSql.setLength(0);
        sqlData().fromSql.append(" from ");

        for (TableDef tableDef : this.sqlData().fromTable) {
            String sql = tableDef.getTableName() + " ";
            String alias = this.sqlData().tableAliasMap.get(tableDef.getTableName());
            if (ChkUtil.isNotNull(alias)) {
                sql += " as " + alias + ",";
            }
            sqlData().fromSql.append(sql);
        }
        // 去掉 列 最后的逗号
        sqlData().fromSql.deleteCharAt(sqlData().fromSql.length() - 1);
        sqlData().fromSql.append(' ');

        return sqlData().fromSql.toString();
    }

}
